IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FUBSplitString]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
	DROP FUNCTION [dbo].[FUBSplitString]
END
GO


-- SELECT * FROM dbo.FUBSplitString ('A,B,C', ',')

CREATE FUNCTION FUBSplitString (@pString VARCHAR (MAX), @pDelimiter CHAR (1))     
   RETURNS @tempTable TABLE (tempItem varchar(MAX), [index] INT)       
AS  
BEGIN       

	DECLARE @idx INT       
	DECLARE @slice VARCHAR (MAX)     
	DECLARE @index INT  


	SET @index = 0

	SELECT @idx = 1       

	IF LEN (@PString) < 1 OR @PString IS NULL
	BEGIN
		RETURN
	END       

	WHILE @idx!= 0       
	BEGIN
       
		SET @idx = CHARINDEX (@pDelimiter, @pString)       
	      
		IF @idx!=0
		BEGIN       
			SET @slice = LEFT (@pString, @idx - 1)       
		END
		ELSE
		BEGIN
			SET @slice = @pString       
		END

		IF (LEN (@slice) > 0)
		BEGIN  
			INSERT INTO @tempTable VALUES (LTRIM (RTRIM (@slice)), @index)       

			SET @index = @index + 1
		END
		
		SET @pString = RIGHT (@pString, LEN (@pString) - @idx)       

		IF LEN (@pString) = 0 
		BEGIN
			BREAK       
		END	   
	END
  
RETURN
END
GO
